package com.copd.service.impl;

import com.copd.entity.Permission;
import com.copd.entity.Role;
import com.copd.mapper.PermissionMapper;
import com.copd.mapper.RoleMapper;
import com.copd.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    
    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    @Override
    public List<Role> getAllRoles() {
        return roleMapper.findAll();
    }
    
    @Override
    public Role getRoleById(Integer roleId) {
        return roleMapper.findById(roleId);
    }
    
    @Override
    public Role getRoleByKey(String roleKey) {
        return roleMapper.findByRoleKey(roleKey);
    }
    
    @Override
    public Role createRole(Role role) {
        roleMapper.insert(role);
        return role;
    }
    
    @Override
    public Role updateRole(Role role) {
        if (roleMapper.update(role) > 0) {
            return role;
        }
        return null;
    }
    
    @Override
    public boolean deleteRole(Integer roleId) {
        return roleMapper.deleteById(roleId) > 0;
    }
    
    @Override
    public List<Role> getRolesByUserId(Integer userId) {
        return roleMapper.findByUserId(userId);
    }
    
    @Override
    public boolean assignPermissionToRole(Integer roleId, Integer permissionId) {
        return roleMapper.addPermissionToRole(roleId, permissionId) > 0;
    }
    
    @Override
    public boolean removePermissionFromRole(Integer roleId, Integer permissionId) {
        return roleMapper.removePermissionFromRole(roleId, permissionId) > 0;
    }
    
    @Override
    public boolean assignRoleToUser(Integer userId, Integer roleId) {
        return roleMapper.addRoleToUser(userId, roleId) > 0;
    }
    
    @Override
    public boolean removeRoleFromUser(Integer userId, Integer roleId) {
        return roleMapper.removeRoleFromUser(userId, roleId) > 0;
    }
    
    @Override
    public Role getRoleWithPermissions(Integer roleId) {
        Role role = roleMapper.findById(roleId);
        if (role != null) {
            List<Permission> permissions = permissionMapper.findByRoleId(roleId);
            role.setPermissions(permissions);
        }
        return role;
    }
    
    @Override
    @Transactional
    public boolean updateRolePermissions(Integer roleId, List<Integer> permissionIds) {
        // 首先移除该角色的所有权限
        roleMapper.removeAllPermissionsFromRole(roleId);
        
        // 然后添加新的权限
        if (permissionIds != null && !permissionIds.isEmpty()) {
            for (Integer permissionId : permissionIds) {
                roleMapper.addPermissionToRole(roleId, permissionId);
            }
        }
        return true;
    }
} 